package com.acce.base.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class Utils {
	
	private static Logger logger = Logger.getLogger(Utils.class);
	
	private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	private static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
	private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyMMddHHmmssSSS");

	/**
	 * 当前时间年月日时分秒
	 * @return  yyyy-MM-dd HH:mm:ss
	 */
	public static String getCurrTime() {
		return df.format(new Date());
	}
	
	public static String getTimeString(String time) {
		try {
			return df.format(sdf.parse(time));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 当前时间年月日时分秒毫秒
	 * @return  yyyyMMddHHmmssSSS
	 */
	public static String getCurrTimeMillions() {
		return sdf.format(new Date());
	}
	
	public static String getCurrTimeSecondsStr() {
		return sdf1.format(new Date());
	}
	
	public static Date getDate(String dateString) {
		Date dt = null;
		try {
			dt = df.parse(dateString);
		} catch (ParseException e) {
			logger.error("parse date error." + e);
		}
		return dt;
	}
	
	/**
	 * 时间差
	 * @param d1
	 * @param d2
	 * @return
	 */
	public static String timeDifs(long d1, long d2){
		long mss = d2 - d1;
		long days = mss / (1000 * 60 * 60 * 24);  
	    long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);  
	    long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);  
	    long seconds = (mss % (1000 * 60)) / 1000;  
	    return days + "-" + hours + "-" + minutes + "-"  
		            + seconds;
	}
	
	/**
	 * 增加减少时间
	 * @param time 时间
	 * @param oper 操作 j加，s减
	 * @param timeType 年月日时分秒
	 * @param num 数
	 * @return
	 * @throws ParseException 
	 */
	public static String timeChange(String time, String oper, String timeType, int num) throws ParseException{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = df.parse(time);
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		if("j".equals(oper)){
			if("Y".equals(timeType)){
				c.add(Calendar.YEAR, num);
			}
			if("M".equals(timeType)){
				c.add(Calendar.MONTH, num);
			}
			if("D".equals(timeType)){
				c.add(Calendar.DAY_OF_MONTH, num);
			}
			if("h".equals(timeType)){
				c.add(Calendar.HOUR_OF_DAY, num);
			}
			if("m".equals(timeType)){
				c.add(Calendar.MINUTE, num);
			}
			if("s".equals(timeType)){
				c.add(Calendar.SECOND, num);
			}
		}else if("s".equals(oper)){
			if("Y".equals(timeType)){
				c.add(Calendar.YEAR, -num);
			}
			if("M".equals(timeType)){
				c.add(Calendar.MONTH, -num);
			}
			if("D".equals(timeType)){
				c.add(Calendar.DAY_OF_MONTH, -num);
			}
			if("h".equals(timeType)){
				c.add(Calendar.HOUR_OF_DAY,-num);
			}
			if("m".equals(timeType)){
				c.add(Calendar.MINUTE, -num);
			}
			if("s".equals(timeType)){
				c.add(Calendar.SECOND, -num);
			}
		}
		return df.format(c.getTime());
	}
	
	public static List<Long> daysBetween(Date smdate,Date bdate)
    {    
		List<Long> list = new ArrayList<Long>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        
        long days = (time2-time1)/(1000 * 60 * 60 * 24);
        long hours = (time2-time1)/(1000 * 60 * 60) - 24*days;
        long minutes = (time2-time1)/(1000 * 60)-24*60*days-60*hours;
        
        list.add(days);
        list.add(hours);
        list.add(minutes);
            
       return list;
    }
	
	public static List<Long> daysBetween(String smdate,String bdate) {
		List<Long> list = new ArrayList<Long>();
        Calendar cal = Calendar.getInstance();
        Date d1 = null, d2 = null;
        try {
        	d1 = df.parse(smdate);
        	d2 = df.parse(bdate);
	    } catch(Exception ex) {
	    	logger.error("parse date error.", ex);
	    }
        cal.setTime(d1);
        long time1 = cal.getTimeInMillis();
        cal.setTime(d2);
        long time2 = cal.getTimeInMillis();
        
        long days = (time2-time1)/(1000 * 60 * 60 * 24);
        long hours = (time2-time1)/(1000 * 60 * 60) - 24*days;
        long minutes = (time2-time1)/(1000 * 60)-24*60*days-60*hours;
        
        list.add(days);
        list.add(hours);
        list.add(minutes);
            
       return list;
    }
	
	public static String makeAtUserId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("KL");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	public static String makeProductId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("PD");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	/**
	 * ������˾��,����Ϊ:CP+��ݺ���λ+��+����+��λ�����,��ʮ��λ��
	 * @return
	 */
	public static String makeCompanyId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("CP");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	/**
	 * 生成部门ID
	 * @return
	 */
	public static String makeDepartmentId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("DP");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	/**
	 * ����������,����ΪPW+���+��+��λ�����,��ʮ��λ��
	 * @return
	 */
	public static String makePasswordId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("PW");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	public static String makeChannelId() {
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("CI");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	public static String makeMarketStoreId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("MS");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	public static String makeLeasingContractId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("LC");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	public static String getUUID(){
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replaceAll("-", "");
	}
	
	public static String makeNotifyId(){
		return getUUID();
	}
	
	/**
	 * 获取IP地址
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public final static String getIpAddress(HttpServletRequest request) throws IOException {
		// ��ȡ��������IP��ַ,���ͨ�������������͸������ǽ��ȡ��ʵIP��ַ

		String ip = request.getHeader("X-Forwarded-For");
		if (logger.isInfoEnabled()) {
			logger.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip);
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
				if (logger.isInfoEnabled()) {
					logger.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip);
				}
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
				if (logger.isInfoEnabled()) {
					logger.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip);
				}
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
				if (logger.isInfoEnabled()) {
					logger.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip);
				}
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
				if (logger.isInfoEnabled()) {
					logger.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip);
				}
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
				if (logger.isInfoEnabled()) {
					logger.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip);
				}
			}
		} else if (ip.length() > 15) {
			String[] ips = ip.split(",");
			for (int index = 0; index < ips.length; index++) {
				String strIp = (String) ips[index];
				if (!("unknown".equalsIgnoreCase(strIp))) {
					ip = strIp;
					break;
				}
			}
		}
		return ip;
	}
	
	public static String serviceMapping(String type, String source){
		String target = null;
		if("u".equals(type.toLowerCase())){
			target = source.replace("A", "U");
		}
		return target;
	}
	
	/**
	 * ����������־Id,����ΪOP+���+��+��λ�����,��ʮ��λ��
	 * @return
	 */
	public static String makeOperId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("OP");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	/**
	 * ������¼��־Id,����ΪLG+���+��+��λ�����,��ʮ��λ��
	 * @return
	 */
	public static String makeLoginId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("LG");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	public static String makePageNum(){
		StringBuffer fm = new StringBuffer(); 
		fm.append(sdf2.format(new Date()));
		return fm.toString();
	}
	
	public static String sendhttp(String serviceAddr, Map<String, String> params){
		String returnString = "";
		logger.info("sendhttp::serviceAddr::" + serviceAddr);
		// 创建默认的httpClient实例.    
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        try{
        	// 创建httppost  
	        HttpPost httppost = new HttpPost(serviceAddr);
	        List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
	        Iterator<String> it = params.keySet().iterator();
	        while(it.hasNext()){
	        	String key = it.next();
	        	String value = params.get(key);
	        	formparams.add(new BasicNameValuePair(key,value));
	        }
	        logger.info("sendhttp::params::" + formparams.toString());
	        UrlEncodedFormEntity uefEntitygs = new UrlEncodedFormEntity(formparams,"UTF-8");
	        httppost.setEntity(uefEntitygs); 
	        CloseableHttpResponse response = httpclient.execute(httppost);  //发送post请求并响应的内容
			try {
				HttpEntity entity = response.getEntity(); 
	            returnString=EntityUtils.toString(entity, "UTF-8");
	            logger.info("sendhttp::return content::" + returnString);
			} catch (Exception e) {
				logger.info("sendhttp erroe::" + e.getMessage());
			}finally{
				response.close();
			}
        }catch(Exception e){
        	logger.info("sendhttp erroe::" + e.getMessage());
        }finally{
        	 // 关闭连接,释放资源    
            try {  
                httpclient.close();  
            } catch (IOException e) {
            	logger.info("sendhttp not close::" + e.getMessage());
            }  
        }
        return returnString;
	}
	
	public static void main(String[] args) throws Exception{
		  Connection conn = null;  
		     PreparedStatement pst = null; 
		ResultSet ret = null;  
		 try {  
			 long s = System.currentTimeMillis();
	            Class.forName("com.mysql.jdbc.Driver");//指定连接类型  
//	            conn = DriverManager.getConnection("jdbc:mysql://rdspx88fueu19wpdx20qpublic.mysql.rds.aliyuncs.com/accedb_mm", "rsd_root_maoming", "rsd_root_maoming_20150821");//获取连接  
//	            pst = conn.prepareStatement("select * from usergoods");//准备执行语句  
	            
//	            conn = DriverManager.getConnection("jdbc:mysql://rdspx88fueu19wpdx20qpublic.mysql.rds.aliyuncs.com/accedb_product", "rds_root_product", "rds_root_product_2016");//获取连接  
//	            pst = conn.prepareStatement("select * from buy_goods");//准备执行语句
	            
	            conn = DriverManager.getConnection("jdbc:mysql://rdspx88fueu19wpdx20qpublic.mysql.rds.aliyuncs.com/accedb_nsy", "rsd_root_nsy", "rsd_root_nsy_2016");//获取连接  
	            pst = conn.prepareStatement("select * from user_list");//准备执行语句
	            ret = pst.executeQuery();//执行语句，得到结果集  
	            while (ret.next()) {  
	                String uid = ret.getString(1);  
	                String ufname = ret.getString(2);  
	                String ulname = ret.getString(3);  
	                String udate = ret.getString(4);  
	                System.out.println(uid + "\t" + ufname + "\t" + ulname + "\t" + udate );  
	            }
	            long e = System.currentTimeMillis();
	            
	            System.out.println((e- s));
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	}
}
